/*
 * @lc app=leetcode.cn id=347 lang=cpp
 *
 * [347] 前 K 个高频元素
 */
#include <vector>
#include <unordered_map>
#include <queue>

using namespace std;

// @lc code=start
class Solution {
public:
    struct cmp {
        bool operator()(pair<int, int>& a, pair<int, int>& b){ return a.second > b.second; }
    };
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int,int> table;
        vector<int> ret;
        for(auto& num:nums)
            table[num]++;
        priority_queue<pair<int,int>,vector<pair<int,int>>,cmp> freqs;
        for(auto& a:table){
            freqs.push(a);
            if(freqs.size()>k) freqs.pop();
        }
        while(freqs.size()){
            // cout<<freqs.top().second;
            ret.insert(ret.begin(),freqs.top().first);
            freqs.pop();
        }
        return ret;
    }
};
// @lc code=end

